package com.easemob.helpdesk.fragment;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.bean.AdminVillage;
import com.easemob.helpdesk.bean.AdminVillageRes;
import com.easemob.helpdesk.bean.OwnerInfoRes;
import com.easemob.helpdesk.bean.UserBuildRes;
import com.easemob.helpdesk.entity.TabEntity;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.TimeInfo;
import com.easemob.helpdesk.widget.AddrSearchView;
import com.easemob.helpdesk.widget.CustomListView;
import com.easemob.helpdesk.widget.CustomViewPager;
import com.easemob.helpdesk.widget.NoScrollGridView;
import com.easemob.helpdesk.widget.TimeSelectView;
import com.easemob.helpdesk.widget.WarpLinearLayout;
import com.easemob.helpdesk.widget.pickerview.SimplePickerView;
import com.easemob.helpdesk.widget.popupwindow.VillageFilterWindow;
import com.flyco.roundview.RoundTextView;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.HDConnectionListener;
import com.hyphenate.kefusdk.chat.HDClient;
import com.hyphenate.kefusdk.manager.main.NoticeManager;
import com.hyphenate.kefusdk.manager.session.CurrentSessionManager;
import com.hyphenate.kefusdk.manager.session.HistorySessionManager;
import com.hyphenate.kefusdk.utils.HDLog;
import com.hyphenate.util.NetUtils;
import com.liyuzhao.badger.BadgeUtil;

import org.w3c.dom.Text;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class MsgFragment extends Fragment implements AddrSearchView.searchListener, TimeSelectView.searchListener  {

    private static final String TAG = MsgFragment.class.getSimpleName();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ArrayList<Fragment> fragments;

    private String[] mTabTitles;
    private CurrentSessionFragment currentSessionFragment;
    private WaitAccessFragment mWaitAccessFragment;
    private HistorySessionFragment historySessionFragment;
    private  void initFindView(View view){
        mViewPager=view.findViewById(R.id.msg_viewpager);

        mTabLayout=view.findViewById(R.id.tablayout);
        ll_right=view.findViewById(R.id.ll_right);
        filterText=view.findViewById(R.id.ib_add_task);
        searchIcon=view.findViewById(R.id.ib_menu_more);
        errorItem=view.findViewById(R.id.rl_error_item);


    }
    protected CustomViewPager mViewPager;

    protected CommonTabLayout mTabLayout;
    protected LinearLayout ll_right;
    public TextView filterText;
    public ImageView searchIcon;

    public RelativeLayout errorItem;
    public TextView errorText;

    private AddrSearchView addrSearchView;
    private TimeSelectView timeSelectView;

    private HDConnectionListener connectionListener;


    public int waitCount;

    public MsgFragment() {
        // Required empty public constructor

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_msg, container, false);
        initFindView(view);

        if (TextUtils.isEmpty(MainActivity.village)){
            mTabTitles = new String[3];
            mTabTitles[0] = "待接入";
            mTabTitles[1] = "当前会话";
            mTabTitles[2] = "历史会话";
        }else {//指挥中心账号即信息端管家
            mTabTitles = new String[2];
            mTabTitles[0] = "当前会话";
            mTabTitles[1] = "历史会话";
        }

//        if ((MainActivity.userId < 217 || (MainActivity.userId > 230 && MainActivity.userId < 245) || MainActivity.userId > 248)) {//除了信息端的管家
//            mTabTitles = new String[3];
//            mTabTitles[0] = "待接入";
//            mTabTitles[1] = "当前会话";
//            mTabTitles[2] = "历史会话";
//        }else {//信息端的管家
//            mTabTitles = new String[2];
//            mTabTitles[0] = "当前会话";
//            mTabTitles[1] = "历史会话";
//
//        }
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mViewPager.setOffscreenPageLimit(1);

        fragments = getFragments();

//        if ((MainActivity.userId < 217 || (MainActivity.userId > 230 && MainActivity.userId < 245) || MainActivity.userId > 248)) {
        if (TextUtils.isEmpty(MainActivity.village)){
        }else {
            initBottomMsgDot(true);
        }

        errorText = (TextView) errorItem.findViewById(R.id.tv_connect_errormsg);

        for (int i = 0; i < mTabTitles.length; i++){
            mTabEntities.add(new TabEntity(mTabTitles[i]));
        }

        mViewPager.setAdapter(new MyPagerAdapter(getActivity().getSupportFragmentManager()));
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (!getResources().getString(R.string.LI_XIAO_SHUANG).equals(MainActivity.productKey)) {
                    if (position == 1 || position == 2) {
                        ll_right.setVisibility(View.VISIBLE);
                    } else {
                        ll_right.setVisibility(View.GONE);
                    }

                    if (MainActivity.userRole == 1 && !TextUtils.isEmpty(MainActivity.village)){//指挥中心只有两个tab
                        if (mTabTitles.length == 2) {
                            if (position == 1) {//历史会话
                                ll_right.setVisibility(View.VISIBLE);
                            } else {
                                ll_right.setVisibility(View.GONE);
                            }
                        }
                    }else {

                    }
//                    if (TextUtils.isEmpty(MainActivity.village)){
////                    if ((MainActivity.userId < 217 || (MainActivity.userId > 230 && MainActivity.userId < 245) || MainActivity.userId > 248)) {//除了信息端的管家
//                        if (position == 1 || position == 2) {
//                            ll_right.setVisibility(View.VISIBLE);
//                        } else {
//                            ll_right.setVisibility(View.GONE);
//                        }
//                    }else {
//                        ll_right.setVisibility(View.VISIBLE);
//                    }


                }else {
                    if (position == 2) {
                        ll_right.setVisibility(View.VISIBLE);
                    } else {
                        ll_right.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mTabLayout.setTabData(mTabEntities);
        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mViewPager.setCurrentItem(position);
//                if(position == 2){// 历史会话
//                    historySessionFragment.onFreshData();
//                }
                if (TextUtils.isEmpty(MainActivity.village)){
//                if ((MainActivity.userId < 217 || (MainActivity.userId > 230 && MainActivity.userId < 245) || MainActivity.userId > 248)) {//除了信息端的管家
                    if (position != 2) {
                        if (timeSelectView != null) {
                            timeSelectView.reset();
                        }
                    }

                    if (position != 1) {
                        if (addrSearchView != null) {
                            addrSearchView.reset();
                        }
                    }
                }else {
                    if (position != 1) {
                        if (timeSelectView != null) {
                            timeSelectView.reset();
                        }
                    }

                    if (position != 0) {
                        if (addrSearchView != null) {
                            addrSearchView.reset();
                        }
                    }
                }

            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        ll_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//<<<<<<< HEAD
//                if (mTabLayout.getCurrentTab() == 1) {//当前会话
//                    if (addrSearchView == null) {
//                        addrSearchView = new AddrSearchView(getActivity(), MsgFragment.this, false);
//                        addrSearchView.showSearchView();
//                        if (currentSessionFragment != null) {
//=======
            if(mTabLayout.getCurrentTab() == mTabTitles.length - 2){//当前会话
                if(addrSearchView == null){
                    addrSearchView = new AddrSearchView(getActivity(), MsgFragment.this, false);
                    addrSearchView.showSearchView();
                    if(currentSessionFragment != null){
                        currentSessionFragment.hideSoftKeyboard();
                    }

                }else {
                    if(addrSearchView.isShowing()){
                        addrSearchView.hideSearchView();
                    }else{
                        addrSearchView.showView();
                        if(currentSessionFragment != null){
//>>>>>>> master
                            currentSessionFragment.hideSoftKeyboard();
                        }

//<<<<<<< HEAD
//                    } else {
//                        if (addrSearchView.isShowing()) {
//                            addrSearchView.hideSearchView();
//                        } else {
//                            addrSearchView.showView();
//                            if (currentSessionFragment != null) {
//                                currentSessionFragment.hideSoftKeyboard();
//                            }
                        }
//=======
                }
            }else if(mTabLayout.getCurrentTab() == mTabTitles.length - 1){//历史会话
                if(timeSelectView == null){
                    timeSelectView = new TimeSelectView(getActivity(), MsgFragment.this);
                    timeSelectView.showSearchView();
                    if(currentSessionFragment != null){
                        currentSessionFragment.hideSoftKeyboard();
                    }
//>>>>>>> master

//                    }
//                } else if (mTabLayout.getCurrentTab() == 2) {//历史会话
//                    if (timeSelectView == null) {
//                        timeSelectView = new TimeSelectView(getActivity(), MsgFragment.this);
//                        timeSelectView.showSearchView();
//                        if (currentSessionFragment != null) {
//                            currentSessionFragment.hideSoftKeyboard();
//                        }

                    } else {
                        if (timeSelectView.isShowing()) {
                            timeSelectView.hideSearchView();
                        } else {
                            timeSelectView.showView();
                            if (currentSessionFragment != null) {
                                currentSessionFragment.hideSoftKeyboard();
                            }
                        }

                    }
                }
            }
        });


        connectionListener = new HDConnectionListener() {
            @Override
            public void onConnected() {
                HDLog.e(TAG, "onConnected");
                if (getActivity() == null){
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (errorItem != null)
                            errorItem.setVisibility(View.GONE);
                        HDLog.e(TAG, "onConnected--error--GONE");
                    }
                });
            }

            @Override
            public void onAuthenticationFailed(int errorCode) {
                if (getActivity() == null){
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Jump to the login UI
                        MainApplication.getInstance().getEventEmitter().sendEvent("logout");

                    }
                });

            }

            @Override
            public void onDisconnected() {
                HDLog.d(TAG, "onDisconnected");
                if (getActivity() == null){
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (errorItem != null)
                            errorItem.setVisibility(View.VISIBLE);
                        if(NetUtils.hasNetwork(getActivity())){
                            errorText.setText("穿越到火星了，请稍后重试");
                        }else{
                            errorText.setText("当前网络不可用，请检查网络设置");
                        }
                    }
                });
            }
        };
        HDClient.getInstance().addConnectionListener(connectionListener);

    }

    private ArrayList<Fragment> getFragments() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        if (currentSessionFragment == null){
            currentSessionFragment = new CurrentSessionFragment();
            currentSessionFragment.setMsgFragment(this);
        }
        if (TextUtils.isEmpty(MainActivity.village)){
//        if ((MainActivity.userId < 217 || (MainActivity.userId > 230 && MainActivity.userId < 245) || MainActivity.userId > 248)) {
            if (mWaitAccessFragment == null) {
                mWaitAccessFragment = new WaitAccessFragment();
            }
        }

        if (historySessionFragment == null){
            historySessionFragment = new HistorySessionFragment();
        }

        if (TextUtils.isEmpty(MainActivity.village)){
//        if ((MainActivity.userId < 217 || (MainActivity.userId > 230 && MainActivity.userId < 245) || MainActivity.userId > 248)) {
            fragments.add(mWaitAccessFragment);
        }
        fragments.add(currentSessionFragment);
        fragments.add(historySessionFragment);

        return fragments;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

//    public void waitIntent(int position, int index){
//        if (mWaitAccessFragment != null){
//            mWaitAccessFragment.clickAccess(position, index);
//        }
//    }

//    public int getWaitTotalCount(){
//        int waitCount = mWaitAccessFragment.getWaitTotalCount();
//        return waitCount;
//    }

    public void selectTopTab(int position){
        mTabLayout.setCurrentTab(position);
        mViewPager.setCurrentItem(position);
    }

    public CommonTabLayout getmTabLayout(){
        return mTabLayout;
    }

    public void refreshWaitUnreadCount() {
        if (mWaitAccessFragment != null) {
            waitCount = mWaitAccessFragment.getWaitTotalCount();

            if (waitCount > 0) {
                mTabLayout.showMsg(0, waitCount);
                mTabLayout.setMsgMargin(0, 1, 10);
                RoundTextView rtv_agent = mTabLayout.getMsgView(0);
                if (rtv_agent != null) {
                    rtv_agent.getDelegate().setBackgroundColor(Color.rgb(234, 84, 4));
                }
            } else {
//                mTabLayout.showMsg(0, 0);
                mTabLayout.getMsgView(0).setText("0");
                mTabLayout.hideMsg(0);
            }

            if (getActivity() != null) {
                ((MainActivity) getActivity()).refreshSessionUnreadCount(waitCount);
            }
        }


    }


    public void refreshCurUnreadCount() {
        if (currentSessionFragment != null) {
            int curCount = currentSessionFragment.getUnreadCount();

            if (curCount > 0) {
                mTabLayout.showMsg(1, curCount);
                mTabLayout.setMsgMargin(1, 1, 10);
                RoundTextView rtv_agent = mTabLayout.getMsgView(1);
                if (rtv_agent != null) {
                    rtv_agent.getDelegate().setBackgroundColor(Color.rgb(234, 84, 4));
                }
            } else {
                mTabLayout.hideMsg(1);
            }
        }
    }


    private void initBottomMsgDot(boolean isInformationClient){
        if (isInformationClient){
            int totalUnReadCount = CurrentSessionManager.getInstance().getTotalUnReadCount();
            if (getActivity() != null) {
                ((MainActivity) getActivity()).refreshSessionUnreadCount(waitCount,true);
            }
        }
    }

    public void clearFilter(){
        if(addrSearchView != null){
            addrSearchView.clearViewData();
        }


        filterText.setTextColor(Color.parseColor("#ffffff"));
        searchIcon.setImageResource(R.drawable.hk_select_icon);
    }

    @Override
    public void addrSearchRes(String search, String city, String curCityPinyin, String village, String building, String unit, String edit_str) {
        currentSessionFragment.query.getText().clear();

        currentSessionFragment.getAdapter().getFilter().filter(search);
        // 如果是清空的话
        if(search.equals("")){
            filterText.setTextColor(Color.parseColor("#ffffff"));
            searchIcon.setImageResource(R.drawable.hk_select_icon);
        }else{
            filterText.setTextColor(Color.parseColor("#FFF16D"));
            searchIcon.setImageResource(R.drawable.hk_select_icon_data);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (connectionListener != null){
            HDClient.getInstance().removeConnectionListener(connectionListener);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (connectionListener != null){
            HDClient.getInstance().removeConnectionListener(connectionListener);
        }

    }

    @Override
    public void addrSearchRes(TimeInfo info) {
        HistorySessionManager historySessionManager = historySessionFragment.getHistorySessionManager();
        if(historySessionManager != null){
            historySessionManager.setCurrentTimeInfo(info.getStartTime(), info.getEndTime());

            historySessionFragment.onFreshData();

            // 如果是本周
            TextView textView = null;
            if(historySessionFragment.recyclerView != null){
                textView = (TextView)historySessionFragment.recyclerView.getEmptyView().findViewById(R.id.emptyText);
            }

            if(info.getTag().equals("week")){
                filterText.setTextColor(Color.parseColor("#ffffff"));
                searchIcon.setImageResource(R.drawable.hk_select_icon);
                if(textView != null){
                    textView.setText("暂无近一周历史会话\n请点击筛选查看更多");
                }

            }else{
                filterText.setTextColor(Color.parseColor("#FFF16D"));
                searchIcon.setImageResource(R.drawable.hk_select_icon_data);
                if(textView != null){
                    textView.setText("暂无会话");
                }
            }
        }
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

    }
}
